package com.ltsznh.android.familybooks.record;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ltsznh.android.familybooks.MainActivity;
import com.ltsznh.android.familybooks.R;
import com.ltsznh.android.familybooks.db.dbo;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class RecordActivity extends Activity {

    protected String invDate = MainActivity.dayString;
    protected String invType = "O";
    protected String invCategory = "";
    protected String invCategory2 = "";
    protected String accountCategory = "";
    protected String account = "";

    protected final ContentValues values = new ContentValues();
    private Spinner categorySpinner;
    private ArrayAdapter<String> categoryAdapter;
    private Spinner category2Spinner;
    private ArrayAdapter<String> category2Adapter;
    private Spinner accountCategorySpinner;
    private ArrayAdapter<String> accountAdapter;
    private Spinner accountSpinner;
    private ArrayAdapter<String> accountCategoryAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);

        ActionBar actionBar = this.getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        initDate();
        initCategory();
        initAccount();
        initPlace();

        initDefaultValue();
    }

    private void initDefaultValue() {
        String sqlString = "select id,invDate,entryTime,invPicture,yuan," +
                "invType,invCategory,invCategory2,accountCategory,account,remark,isInvalid,place," +
                "longitude,latitude,accuracy,placeTime from inv_blotters where invType = ? order by entryTime desc limit 0,1";
        dbo.getReadableDatabase(this);
        Cursor recordCursor = dbo.fbSQLite.rawQuery(sqlString, new String[]{invType});
        if(recordCursor.getCount()>0){
            recordCursor.moveToFirst();

            invCategory = recordCursor.getString(recordCursor.getColumnIndex("invCategory"));
            int i = categoryAdapter.getCount();
            for(int j = 0;j < i;j++){
                if(categoryAdapter.getItem(j).equalsIgnoreCase(invCategory)){
                    categorySpinner.setSelection(j,true);
                    break;
                };
            }

            accountCategory = recordCursor.getString(recordCursor.getColumnIndex("accountCategory"));
            i = accountCategoryAdapter.getCount();
            for(int j = 0;j < i;j++){
                if(accountCategoryAdapter.getItem(j).equalsIgnoreCase(accountCategory)){
                    accountCategorySpinner.setSelection(j,true);
                };
            }

        }
        recordCursor.close();
        dbo.closeDatabase();

    }

    public void selectDate(View view){
        DatePickerDialog.OnDateSetListener test = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                Calendar invCalendar = Calendar.getInstance();
                invCalendar.set(year,month,day);
                invDate = MainActivity.format.format(invCalendar.getTime());
                initDate();
            }
        };

        DatePickerDialog invDatePicker;
        invDatePicker = new DatePickerDialog(this,test,Integer.parseInt(invDate.substring(0,4)),
                Integer.parseInt(invDate.substring(5,7)) - 1,Integer.parseInt(invDate.substring(8,10)));
        invDatePicker.show();
    }

    private void initDate() {
        EditText invDateText = (EditText) findViewById(R.id.editText_record_date);
        invDateText.setText(invDate);
    }

    private void initCategory(){
        //类别1
        categorySpinner = (Spinner) findViewById(R.id.spinner_record_category);
        categoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categorySpinner.setAdapter(categoryAdapter);

        //类别2
        category2Spinner = (Spinner) findViewById(R.id.spinner_record_category2);
        category2Adapter = new ArrayAdapter<String>(RecordActivity.this, android.R.layout.simple_spinner_item);
        category2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        category2Spinner.setAdapter(category2Adapter);

        String sqlString = "SELECT distinct invCategory FROM inv_category where isEnabled = 'Y' AND invType='" + invType + "' order by displayOrder";
        dbo.getReadableDatabase(this);
        Cursor CategoryCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(CategoryCursor.getCount()>0){
            CategoryCursor.moveToFirst();
            do{
                categoryAdapter.add(CategoryCursor.getString(0));
            }while (CategoryCursor.moveToNext());
        }
        CategoryCursor.close();
        dbo.closeDatabase();

        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                invCategory = categoryAdapter.getItem(i);
                selectCategory2();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    }

    private void selectCategory2() {
        category2Adapter.clear();
        String sqlString = "SELECT distinct invCategory2 FROM inv_category where isEnabled = 'Y' AND invType='" + invType + "' " +
                "AND invCategory ='" + invCategory + "' order by displayOrder";
        dbo.getReadableDatabase(RecordActivity.this);
        Cursor category2Cursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(category2Cursor.getCount()>0){
            category2Cursor.moveToFirst();
            do{
                category2Adapter.add(category2Cursor.getString(0));
            }while (category2Cursor.moveToNext());
        }
        category2Cursor.close();
        dbo.closeDatabase();

        category2Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                invCategory2 = category2Adapter.getItem(i);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) { }
        });
        initDefaultCategory2();
    }

    private void initDefaultCategory2() {
        String sqlString = "select id,invDate,entryTime,invPicture,yuan," +
                "invType,invCategory,invCategory2,accountCategory,account,remark,isInvalid,place," +
                "longitude,latitude,accuracy,placeTime from inv_blotters where invType = ? and invCategory = ? order by entryTime desc limit 0,1";
        Log.d(this.getLocalClassName(),sqlString);
        dbo.getReadableDatabase(this);
        Cursor recordCursor = dbo.fbSQLite.rawQuery(sqlString, new String[]{invType,invCategory});
        if(recordCursor.getCount()>0){
            recordCursor.moveToFirst();

            String invCategory2Tmp = recordCursor.getString(recordCursor.getColumnIndex("invCategory2"));
            int i = category2Adapter.getCount();
            category2Spinner.setSelection(0,true);
            for(int j = 0;j < i;j++){
                if(category2Adapter.getItem(j).equalsIgnoreCase(invCategory2Tmp)){
                    category2Spinner.setSelection(j,true);
                };
            }
        }
        recordCursor.close();
        dbo.closeDatabase();

    }

    private void initAccount() {
        //账户类别
        accountCategorySpinner = (Spinner) findViewById(R.id.spinner_record_accountCategory);
        accountCategoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        accountCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        accountCategorySpinner.setAdapter(accountCategoryAdapter);
        //账户
        accountSpinner = (Spinner) findViewById(R.id.spinner_record_account);
        accountAdapter = new ArrayAdapter<String>(RecordActivity.this, android.R.layout.simple_spinner_item);
        accountAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        accountSpinner.setAdapter(accountAdapter);

        String sqlString = "select distinct accountCategory from inv_account where isEnabled ='Y' order by displayOrder";
        dbo.getReadableDatabase(this);
        Cursor accountCategoryCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(accountCategoryCursor.getCount()>0){
            accountCategoryCursor.moveToFirst();
            do{
                accountCategoryAdapter.add(accountCategoryCursor.getString(0));
            }while (accountCategoryCursor.moveToNext());
        }
        accountCategoryCursor.close();
        dbo.closeDatabase();

        accountCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                账户
                accountCategory = accountCategoryAdapter.getItem(i);
                selectAccount();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    }

    private void selectAccount() {
        accountAdapter.clear();
        String sqlString = "select distinct account from inv_account where isEnabled ='Y' " +
                "and accountCategory ='" + accountCategory + "'  order by displayOrder";
        dbo.getReadableDatabase(RecordActivity.this);
        Cursor accountCursor = dbo.fbSQLite.rawQuery(sqlString, null);
        if(accountCursor.getCount()>0){
            accountCursor.moveToFirst();
            do{
                accountAdapter.add(accountCursor.getString(0));
            }while (accountCursor.moveToNext());
        }
        accountCursor.close();
        dbo.closeDatabase();

        accountSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                account = accountAdapter.getItem(i);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
        initDefaultAccount();
    }

    private void initDefaultAccount(){
        String sqlString = "select id,invDate,entryTime,invPicture,yuan," +
                "invType,invCategory,invCategory2,accountCategory,account,remark,isInvalid,place," +
                "longitude,latitude,accuracy,placeTime from inv_blotters where invType = ? and accountCategory = ? order by entryTime desc limit 0,1";
        dbo.getReadableDatabase(this);
        Cursor recordCursor = dbo.fbSQLite.rawQuery(sqlString, new String[]{invType,accountCategory});
        if(recordCursor.getCount()>0){
            recordCursor.moveToFirst();
            String accountTmp = recordCursor.getString(recordCursor.getColumnIndex("account"));
            int i = accountAdapter.getCount();
            accountSpinner.setSelection(0,true);
            for(int j = 0;j < i;j++){
                if(accountAdapter.getItem(j).equalsIgnoreCase(accountTmp)){
                    accountSpinner.setSelection(j,true);
                };
            }
        }
        recordCursor.close();
        dbo.closeDatabase();
    }

    private void initPlace(){
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取GPS信息并显示
        //1、通过GPS位置提供器获得位置(指定具体的位置提供器
        String provider=LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);
        //2、使用标准集合，让系统自动选择可用的最佳位置提供器，提供位置
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);//高精度
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);//不允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
        //从可用的位置提供器中，匹配以上标准的最佳提供器
        provider = locationManager.getBestProvider(criteria, true);
        //获得最后一次变化的位置
        location = locationManager.getLastKnownLocation(provider);
        //监听位置变化，2秒一次，距离2米以上
//        locationManager.requestLocationUpdates(provider, 100, 0, locationListener);

        updateWithNewLocation(location);
    }
    protected void updateWithNewLocation(Location location){
        if(location != null){
            values.put("longitude", location.getLongitude() + "");
            values.put("latitude", location.getLatitude() + "");
            values.put("accuracy", location.getAccuracy() + "");
            values.put("placeTime",  location.getTime());

            TextView longitude_latitude = (TextView) findViewById(R.id.textView_record_longitude_latitude);
            longitude_latitude.setText((new SimpleDateFormat("yyyy/MM/dd hh:mm:ss")).format(values.get("placeTime")) + "/" +
                    values.get("longitude").toString().substring(0, 4) + "/" + values.get("latitude").toString().substring(0, 4) + "/" +
                    values.get("accuracy").toString().substring(0, 3) + "/" + location.getProvider());
        }else {
            Log.d(this.getLocalClassName(),"location null");
        }
    }

    private void initDataValue() {
        values.put("invDate",invDate);
        values.put("invType",invType);

        values.put("invCategory",invCategory);
        values.put("invCategory2",invCategory2);
        values.put("accountCategory",accountCategory);
        values.put("account",account);

        values.put("yuan",((EditText) findViewById(R.id.editText_record_yuan)).getText().toString());
        values.put("place",((EditText) findViewById(R.id.editText_record_place)).getText().toString());
        values.put("remark",((EditText) findViewById(R.id.editText_record_remark)).getText().toString());
    }

    public void saveData(View view){
        initDataValue();
        long i = dbo.insertData(this, "inv_blotters", null, values);
        if(i == -1){
            Toast.makeText(this,"ERROR",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"OK",Toast.LENGTH_SHORT).show();
            goBack();
        }
//        initDefaultValue2();
//        Log.d("TTTT",category2Adapter.getCount()  + "/" + accountAdapter.getCount() + "/" + accountSpinner.getCount());
    }

    protected void goBack(){
//        Log.d(this.getClass().toString(),  "to home");
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
//        this.finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                goBack();
                return true;
            case R.id.action_in:
                Log.d(this.getClass().toString(), "action in");
                invType = "I";
                initCategory();
                initDefaultValue();
                return true;
            case R.id.action_out:
                Log.d(this.getClass().toString(), "action out");
                invType = "O";
                initCategory();
                initDefaultValue();
                return true;
            default:
                Log.d(this.getClass().toString(),"nothing");
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.record, menu);
        return true;
    }
}
